package com.binance.notification.web.service.helper;

import java.time.Duration;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.binance.master.utils.ThreadUtils;
import org.springframework.stereotype.Service;

import com.binance.assetservice.api.IProductApi;
import com.binance.assetservice.vo.request.product.FetchProductsRequest;
import com.binance.assetservice.vo.response.product.FetchProductsResponse;
import com.binance.master.error.GeneralCode;
import com.binance.master.models.APIRequest;
import com.binance.master.models.APIResponse;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ProductService  {

    @Resource
    private IProductApi productApi;
    private static final String ALL_PRODUCT_CACHE_KEY = "all_product_cache_key";
//    private static final String CNY_USD_CACHE_KEY = "cny_usd_cache_key";

    // 缓存所有产品信息，每隔10分钟更新一次
    private LoadingCache<String, List<FetchProductsResponse>> productCache = CacheBuilder.newBuilder()
            .expireAfterWrite(Duration.ofMinutes(30)).build(new CacheLoader<String, List<FetchProductsResponse>>() {

                @Override
                public List<FetchProductsResponse> load(String key) throws Exception {
                    return loadAllProducts();
                }

            });
    // 人民币对美元汇率本地缓存，每5分钟更新一次
//    private LoadingCache<String, Double> cnyusdCache =
//            CacheBuilder.newBuilder().expireAfterWrite(Duration.ofMinutes(5)).build(new CacheLoader<String, Double>() {
//
//                @Override
//                public Double load(String key) throws Exception {
//                    APIResponse<Double> response = productApi.cnyusd(APIRequest.instanceBodyNull());
//                    if (GeneralCode.SUCCESS.getCode().equals(response.getCode())) {
//                        return response.getData();
//                    }
//                    log.warn("从asset-service获取cnyusd出错：{}", response.toString());
//                    throw new Exception(response.toString());
//                }
//
//            });

    private List<FetchProductsResponse> loadAllProducts() throws Exception {
        FetchProductsRequest body = new FetchProductsRequest();
        APIResponse<List<FetchProductsResponse>> response = productApi.fetchProducts(APIRequest.instance(body));
        if (GeneralCode.SUCCESS.getCode().equals(response.getCode())) {
            return response.getData();
        }
        log.warn("从asset-service获取AllProducts出错：{}", response.toString());
        throw new Exception(response.toString());
    }

    public List<FetchProductsResponse> getAllProducts() throws Exception {
        return this.productCache.get(ALL_PRODUCT_CACHE_KEY);
    }

//    public Double getCnyUsd() {
//        try {
//            return this.cnyusdCache.get(CNY_USD_CACHE_KEY);
//        } catch (ExecutionException e) {
//            log.error("获取缓存的cnyusd出错", e);
//            return 6.6;
//        }
//    }

    @PostConstruct
    public void init() {
        try {
            this.getAllProducts();
        } catch (Exception e) {
            log.error("从asset-service加载所有产品到本地出现错误：",e);
            ThreadUtils.sleep(10 * 3000);
            System.exit(-1);
        }
//        this.getCnyUsd();
    }
}
